<template>
    <div class="layout-route online-detail">
        <div class="header"><el-button icon="el-icon-arrow-left" @click="cancel">返回</el-button> <span class="header-title">{{model.id? '编辑': '新增'}}公共产品</span></div>
        <el-form ref="form" :model="model" :rules="rules" label-width="120px" inline v-loading="loading">
            <div class="card">
                <div class="title">基础信息</div>
                <el-form-item label="店铺" prop="shop_id" v-if="isPrivate">
                    <el-select v-model="model.shop_id" placeholder="请选择店铺" filterable clearable size="small" :disabled="!!model.id" @change="selectShop">
                        <el-option v-for="(dict, index) in dict.shopList" :key="index" :label="dict.shop_name" :value="dict.shop_id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="类型" prop="product_variant_type">
                    <el-radio-group v-model="model.product_variant_type" size="small">
                        <el-radio :label="1">单品</el-radio>
                        <el-radio :label="2">多变体</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="产品标题" prop="product_title">
                    <el-input v-model="model.product_title" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="产品spu" prop="spu">
                    <el-input v-model.trim="model.spu" placeholder="请输入产品spu" clearable></el-input>
                </el-form-item>
                <el-form-item label="产品标签">
                    <el-select v-model="model.product_tags" allow-create multiple filterable default-first-option placeholder="请输入标签"></el-select>
                </el-form-item>
                <el-form-item label="产品描述">
                    <editor v-model="model.product_desc"></editor>
                </el-form-item>
                <el-form-item label="Collections" v-if="isPrivate">
                    <el-select v-model="model.collections_tag" multiple filterable remote :remote-method="remoteQueryCollection" placeholder="请选择Collections">
                        <el-option v-for="item in dict.collectionList" :key="item.id" :label="item.collection" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分类" prop="product_type">
                    <el-select v-model="model.product_type" placeholder="请选择分类" clearable>
                        <el-option v-for="(dict, index) in dict.productTypeList" :key="index" :label="dict.type_name" :value="dict.type_id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="供应商" prop="supply_shop_name" class="half" v-if="isPrivate">
                    <el-input v-model="model.supply_shop_name" placeholder="最多可输入255字符" maxlength="255"></el-input>
                </el-form-item>
                <el-form-item label="渠道URL" prop="supply_url" class="half">
                    <el-input v-model="model.supply_url" placeholder="最多可输入255字符" maxlength="255"></el-input>
                </el-form-item>
                <template v-if="isSingleSku">
                    <el-form-item label="SKU" prop="sku" class="half">
                        <el-input v-model="model.sku" placeholder="最多可输入255字符" maxlength="255"></el-input>
                    </el-form-item>
                    <el-form-item label="Barcode" class="half">
                        <el-input v-model="model.barcode" placeholder="最多可输入255字符" maxlength="255"></el-input>
                    </el-form-item>
                </template>
            </div>
            <div class="card" v-if="isSingleSku">
                <div class="title">价格与存储</div>
                <el-form-item label="售价" prop="price" class="half">
                    <el-input v-model="model.price" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="MSRP" prop="compare_at_price" class="half">
                    <el-input v-model="model.compare_at_price" placeholder="" />
                </el-form-item>
                <el-form-item label="库存" prop="inventory_quantity" class="half">
                    <el-input v-model="model.inventory_quantity" placeholder="" :disabled="model.inventory_support == 3"></el-input>
                </el-form-item>
                <el-form-item label="库存方式" prop="inventory_support" class="half">
                    <el-select v-model="model.inventory_support" placeholder="">
                        <el-option label="支持负库存购买" value="1"></el-option>
                        <el-option label="不支持负库存购买" value="2"></el-option>
                        <el-option label="不填写库存" value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="重量" prop="weight" class="half">
                    <el-input v-model="model.weight" placeholder="">
                        <span slot="append">kg</span>
                    </el-input>
                </el-form-item>
            </div>
            <div class="card">
                <div class="title">图片信息</div>
                <el-form-item label="图片" prop="product_images" class="full">
                    <div>
                        <el-tag>说明！ </el-tag>点击图片拖动，即可调整图片顺序！ 「图片最多选用<span style="color: #ff4949">200</span>张，已经选用了<span style="color: #11a983">{{ imageLength }}</span
                        >张
                    </div>
                    <ImageUploadMultiple v-model="model.product_images" :limit="200" :drag="true"></ImageUploadMultiple>
                </el-form-item>
            </div>
            <div class="card" v-if="isMultipleSku">
                <div class="title">变体属性</div>
                <el-row type="flex" align="middle" style="margin-bottom: 12px">
                    <span style="font-size: 14px">变种主题：</span>
                    <el-checkbox-group v-model="attrs">
                        <el-checkbox label="Color">Color</el-checkbox>
                        <el-checkbox label="Size">Size</el-checkbox>
                        <el-checkbox label="CupSize">CupSize</el-checkbox>
                        <el-checkbox :label="custom.name" v-for="(custom, index) in customList" :key="index">{{ custom.name }}</el-checkbox>
                    </el-checkbox-group>
                    <div style="display: flex; align-items: center; margin-left: 24px">
                        <el-input v-model="attrName" style="width: 200px"></el-input>
                        <el-button @click="addCustomAttr">添加自定义主题</el-button>
                    </div>
                </el-row>
                <el-form-item label="Color" v-if="attrs.includes('Color')" class="item-card">
                    <div class="el-checkbox-group">
                        <div :class="['el-checkbox', isChecked(item.id, fullColors) ? 'is-checked' : '']" @click="selectColors(item)" v-for="item in dict.colorList" :key="item.id">
                            <span :class="['el-checkbox__input', isChecked(item.id, fullColors) ? 'is-checked' : '']">
                                <span class="el-checkbox__inner"></span>
                                <input type="checkbox" class="el-checkbox__original" v-model="item.attr_name" />
                            </span>
                            <span class="el-checkbox__label">{{ item.attr_name }}</span>

                            <span class="checkbox-delete" style="padding: 0 4px" @click.stop="deleteColor(item)" v-if="item.type == 'new'"><i class="el-icon-circle-close"></i></span>
                        </div>
                        <div>
                            <el-input v-model="customColor" placeholder="输入要添加的属性" style="width: 200px"></el-input>
                            <el-button type="primary" icon="el-icon-plus" @click="addColor">添加</el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="Size" v-if="attrs.includes('Size')" class="item-card">
                    <div class="el-checkbox-group">
                        <div :class="['el-checkbox', isChecked(item.id, fullLetterSizes) ? 'is-checked' : '']" @click="selectLetterSizes(item)" v-for="item in dict.letterSizeList" :key="item.id">
                            <span :class="['el-checkbox__input', isChecked(item.id, fullLetterSizes) ? 'is-checked' : '']">
                                <span class="el-checkbox__inner"></span>
                                <input type="checkbox" class="el-checkbox__original" v-model="item.attr_name" />
                            </span>
                            <span class="el-checkbox__label">{{ item.attr_name }}</span>
                            <span class="checkbox-delete" style="padding: 0 4px" @click.stop="deleteCustomItem(item, dict.letterSizeList)" v-if="item.type == 'new'"
                                ><i class="el-icon-circle-close"></i
                            ></span>
                        </div>
                        <div>
                            <el-input v-model="customLetterSize" placeholder="输入要添加的属性" style="width: 200px"></el-input>
                            <el-button type="primary" icon="el-icon-plus" @click="addLetterSize">添加</el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="CupSize" v-if="attrs.includes('CupSize')" class="item-card">
                    <el-checkbox-group v-model="model.sizes">
                        <el-checkbox :label="item.attr_name" v-for="item in dict.sizeList" :key="item.id"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="Cup" v-if="attrs.includes('CupSize')" key="sup_cup_key" class="item-card">
                    <el-checkbox-group v-model="model.cups">
                        <el-checkbox :label="item.attr_name" v-for="item in dict.cupList" :key="item.id"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <template v-for="(custom, index) in customList">
                    <el-form-item :key="index" class="item-card" v-if="attrs.includes(custom.name)">
                        <template #label>
                            <!-- <attrLabel v-model="custom.name" @removeAttr="removeAttr"></attrLabel> -->
                            <span>{{ custom.name }}</span>
                            <!-- <el-input v-model="custom.name" @blur="getName(index)" placeholder="属性名" style="width: 100px"></el-input> -->
                        </template>
                        <div class="el-checkbox-group">
                            <div :class="['el-checkbox', isChecked(item.id, custom.fullList) ? 'is-checked' : '']" @click="selectDiameter(item, custom)" v-for="item in custom.fullList" :key="item.id">
                                <span :class="['el-checkbox__input', isChecked(item.id, custom.fullList) ? 'is-checked' : '']">
                                    <span class="el-checkbox__inner"></span>
                                    <input type="checkbox" class="el-checkbox__original" v-model="item.attr_name" disabled />
                                </span>
                                <span class="el-checkbox__label">{{ item.attr_name }}</span>
                                <span class="checkbox-delete" style="padding: 0 4px" @click.stop="deleteCustomItem(item, custom.data)"><i class="el-icon-circle-close"></i></span>
                            </div>
                            <!-- <el-input v-model="custom.value" :placeholder="`添加${custom.name || '自定义属性'}`" @blur="addCustomItem(custom.value, custom)" style="width: 200px"></el-input> -->
                            <div>
                                <el-input v-model="custom.value" placeholder="输入要添加的属性" style="width: 200px"></el-input>
                                <el-button type="primary" icon="el-icon-plus" @click="addCustomItem(custom.value, custom)">添加</el-button>
                                <span style="padding: 0 8px" @click.stop="deleteCustom(index)"><i class="el-icon-delete" style="font-size: 18px"></i></span>
                            </div>
                        </div>
                    </el-form-item>
                </template>
                <!-- <el-button @click="addCustom">新增属性</el-button> -->
            </div>
            <div class="card" v-if="isMultipleSku">
                <div class="title">变种信息</div>
                <el-row type="flex" justify="end">
                    <el-checkbox v-model="showStockSupport">显示库存支持</el-checkbox>
                </el-row>
                <el-table :data="model.variant_json" border script v-if="model.variant_json.length > 0">
                    <el-table-column label="图片" width="100">
                        <template slot-scope="scope">
                            <ImageUploadImg
                                v-model="scope.row.image_url"
                                :limit="1"
                                :multiple="false"
                                :popoverDisabled="false"
                                :hoverType="'copy'"
                                @copyToOther="
                                    val => {
                                        copyImgToOther(val, scope.row)
                                    }
                                "
                            ></ImageUploadImg>
                        </template>
                    </el-table-column>
                    <el-table-column label="Color" prop="Color" v-if="attrs.includes('Color')" width="85"></el-table-column>
                    <el-table-column label="Size" prop="Size" v-if="attrs.includes('Size')" width="85"></el-table-column>
                    <el-table-column label="CupSize" prop="CupSize" v-if="attrs.includes('CupSize')" width="85"></el-table-column>
                    <el-table-column label="Cup" prop="Cup" v-if="attrs.includes('CupSize')" width="85"></el-table-column>
                    <el-table-column :label="custom.name" :prop="custom.name" v-for="(custom, index) in customList" :key="index" width="85"></el-table-column>
                    <el-table-column label="SKU" min-width="160">
                        <template #header>
                            <div>SKU</div>
                            <div class="ml_12">（<span style="color: #11a983; cursor: pointer" @click="showSeniorDialog">高级</span>）</div>
                        </template>
                        <template slot-scope="scope">
                            <el-input v-model.trim="scope.row.sku"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="Barcode" min-width="80">
                        <template #header>
                            <div>Barcode</div>
                            <div>（<span style="color: #11a983; cursor: pointer" @click="showBatchDialog('barcode')">批量</span>）</div>
                        </template>
                        <template slot-scope="scope">
                            <el-input v-model.trim="scope.row.barcode" placeholder="请输入"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="价格" min-width="80">
                        <template #header>
                            <div>价格</div>
                            <div class="ml_12">（<span style="color: #11a983; cursor: pointer" @click="showBatchDialog('price')">批量</span>）</div>
                        </template>
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.price" placeholder=""></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="MSRP" min-width="80">
                        <template #header>
                            <div>MSRP</div>
                            <div style="margin-left: -6px">（<span style="color: #11a983; cursor: pointer" @click="showBatchDialog('compare_at_price')">批量</span>）</div>
                        </template>
                        <template slot-scope="scope">
                            <el-input type="input" v-model.trim="scope.row.compare_at_price" placeholder=""></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存" min-width="80">
                        <template #header>
                            <div>库存</div>
                            <div class="ml_12">（<span style="color: #11a983; cursor: pointer" @click="showBatchDialog('inventory_quantity')">批量</span>）</div>
                        </template>
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.inventory_quantity" placeholder=""></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存支持" min-width="80" v-if="showStockSupport">
                        <template #header>
                            <div>库存支持</div>
                            <div>（<span style="color: #11a983; cursor: pointer" @click="showBatchDialog('inventory_support')">批量</span>）</div>
                        </template>
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.inventory_support" placeholder="">
                                <el-option label="支持负库存购买" :value="1"></el-option>
                                <el-option label="不支持负库存购买" :value="2"></el-option>
                                <el-option label="不填写库存" :value="3"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="重量" min-width="80">
                        <template #header>
                            <div>重量</div>
                            <div class="ml_12">（<span style="color: #11a983; cursor: pointer" @click="showBatchDialog('weight')">批量</span>）</div>
                        </template>
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.weight" placeholder="">
                                <span slot="append">kg</span>
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" fixed="right">
                        <template slot-scope="scope">
                            <el-button type="text" @click="removeVariant(scope.row)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="card" v-if="isPrivate">
                <div class="title" style="margin-bottom: 0">搜索引擎优化(SEO)<i :class="!showSeo ? 'el-icon-circle-plus-outline' : 'el-icon-remove-outline'" style="margin: 4px 0 0 4px; cursor: pointer" @click="showSeoTemp"></i></div>
                <template v-if="showSeo">
                    <el-form-item label="标题" prop="seo_title" style="margin-top: 16px">
                        <el-input v-model="model.seo_title" placeholder="" :maxlength="300" show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item label="描述" prop="seo_desc">
                        <el-input v-model="model.seo_desc" type="textarea" placeholder="" :maxlength="1000" show-word-limit />
                    </el-form-item>
                    <el-form-item label="URL" prop="seo_url">
                        <el-input v-model="model.seo_url" placeholder="">
                            <template slot="prepend" v-if="isPrivate">{{ myshopify_domain }}</template>
                            <template slot="append"><span @click="copyTitleToUrl" style="cursor: pointer">复制</span></template>
                        </el-input>
                    </el-form-item>
                </template>
            </div>
            <div style="text-align: right; padding: 24px 0;">
                <el-button type="primary" :loading="save" :disabled="save" @click="submit">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-form>
        <el-dialog title="SKU高级生成规则" :visible.sync="seniorVisible" width="1400px" append-to-body>
            <el-form ref="formSenior" :model="modelSenior" label-width="200px">
                <el-form-item label="第一步：设置前后缀">
                    <el-input v-model.trim="modelSenior.prefix" placeholder="示例：GX" style="width: 200px; margin-right: 16px" @input="getPreviewValue">
                        <template slot="prepend">前缀</template>
                    </el-input>
                    <el-input v-model.trim="modelSenior.character" placeholder="示例：-" style="width: 200px; margin-right: 16px" @input="getPreviewValue">
                        <template slot="prepend">连接符</template>
                    </el-input>
                    <el-input v-model.trim="modelSenior.suffix" placeholder="示例：US" style="width: 200px" @input="getPreviewValue">
                        <template slot="prepend">后缀</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="第二步：SKU顺序">
                    <el-tag size="large" v-for="(item, index) in modelSenior.attrList" :key="index" style="margin-right: 16px">{{ item.name }}</el-tag>
                </el-form-item>
                <el-form-item label="第三步：设置变种代码">
                    <el-collapse v-model="activeNames">
                        <el-collapse-item :name="item.name" v-for="(item, index) in modelSenior.attrList" :key="index">
                            <template slot="title">
                                <span style="font-size: 18px; font-weight: bold">{{ item.name }}</span>
                            </template>
                            <div style="display: flex">
                                <div v-for="(temp, tempIndex) in item.data" :key="tempIndex" style="margin: 8px 32px 8px 0">
                                    <span>{{ temp.value }}</span>
                                    <el-input v-model="temp.editValue" style="width: 200px" @input="getPreviewValue"></el-input>
                                </div>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </el-form-item>
                <el-form-item label="第四步：SKU生成预览">
                    <el-input v-model="modelSenior.previewValue"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="seniorSave">确 定</el-button>
                <el-button @click="seniorVisible = false">取 消</el-button>
            </div>
        </el-dialog>
        <batchEditDialog v-model="batchDialog.visible" :type="batchDialog.type" @change="batchEditVariant"></batchEditDialog>
    </div>
</template>

<script>
import { getAttrList, getSkuAttr, addColor, deleteColor } from '@/api/product'
import { getInfo, add, edit, getListingShop, getCollections } from '@/api/listing'
import { SKU_COLOR, SKU_SIZE } from '../constant'
import { deepClone } from '@/utils'
import attrLabel from './components/attr-label.vue'
import batchEditDialog from './components/batchEditDialog.vue'
export default {
    name: 'OnLineDetail',
    components: {
        attrLabel,
        batchEditDialog,
    },
    props: {
        params: {
            type: Object,
            default() {
                return {}
            },
        },
    },
    data() {
        return {
            showStockSupport: false,
            showSeo: false,
            attrs: [],
            activeNames: 'color',
            loading: false,
            save: false,
            sizeModel: 'CupSize',
            myshopify_domain: '',
            model: {
                id: '',
                shop_id: '',
                product_variant_type: 2,
                product_name: '',
                product_images: [],
                sku: '',
                product_tags: '',
                product_desc: '',
                collections_tag: '',
                product_type: '',
                supply_shop_name: '',
                barcode: '',
                price: '',
                compare_at_price: '',
                inventory_quantity: '',
                inventory_support: '1',
                weight: '',
                supply_url: '',
                options: [],
                variant_json: [],
                colors: [],
                sizes: [],
                cups: [],
                seo_title: '',
                seo_desc: '',
                seo_url: '',
            },
            fullColors: [],
            fullLetterSizes: [],
            customList: [],
            customDefault: {
                name: '',
                data: [],
                fullList: [],
            },
            autoVisible: false,
            modelAuto: {
                prefix: '',
                suffix: '',
            },
            seniorVisible: false,
            modelSenior: {
                prefix: '',
                character: '',
                before_character: '',
                suffix: '',
                attrList: [],
                previewValue: '',
            },
            rules: {},
            SKU_COLOR,
            SKU_SIZE,
            dict: {
                collectionList: [],
                productTypeList: [],
                shopList: [],
                colorList: [],
                sizeList: [],
                letterSizeList: [],
                cupList: [],
            },
            customColor: '',
            customLetterSize: '',
            attrName: '',
            collectKeyword: '',
            batchDialog: {
                visible: false,
                type: '',
            },
            isOperate: false, // 正在操作中 不用修改
        }
    },
    computed: {
        imageLength() {
            if (!this.model.product_images) {
                return 0
            } else {
                if (Array.isArray(this.model.product_images)) {
                    return this.model.product_images.length
                } else {
                    return this.model.product_images.split(',').length
                }
            }
        },
        isSingleSku() {
            return this.model.product_variant_type == 1
        },
        isMultipleSku() {
            return this.model.product_variant_type == 2
        },
        isPrivate() {
            // return this.$route.query.model == 'private'
            return false
        },
    },
    watch: {
        params: {
            handler(val) {
                if (val) {
                    this.model.id = val.id
                    if (this.model.id) {
                        this.getDetail()
                    }
                }
            },
            deep: true,
        },
        'model.colors': {
            handler(val) {
                if (!this.isOperate) {
                    this.setVariantArr()
                }
            },
            immediate: true,
            deep: true,
        },
        'model.sizes': {
            handler(val) {
                if (!this.isOperate) {
                    this.setVariantArr()
                }
            },
            immediate: true,
            deep: true,
        },
        'model.cups': {
            handler(val) {
                if (!this.isOperate) {
                    this.setVariantArr()
                }
            },
            immediate: true,
            deep: true,
        },
        customList: {
            handler(val) {
                if (!this.isOperate) {
                    this.setVariantArr()
                }
            },
            immediate: true,
            deep: true,
        },
        'model.shop_id': {
            handler(val) {
                if (val) {
                    this.getCollections()
                }
            },
            immediate: true,
        },
        attrs: {
            handler(newVal, oldVal) {
                const attrs = this.attrs
                const includesSize = newVal?.includes('CupSize')
                const includesLetterSize = newVal?.includes('Size')
                const includesColor = newVal?.includes('Color')
                if (newVal.length > 3) {
                    this.$message.error('最多选择3个变种属性')
                    this.attrs = oldVal
                } else {
                    if (includesColor && !oldVal?.includes('Color')) {
                        // 'Color'置顶为第一个
                        const attrs = newVal.filter(attr => attr !== 'Color')
                        this.attrs = ['Color', ...attrs]
                    }
                    if (includesLetterSize && oldVal?.includes('CupSize')) {
                        // 移除 'CupSize' 和 'Cup'
                        this.attrs = attrs.filter(attr => attr !== 'CupSize')
                        this.model.sizes = []
                    } else if (includesSize && oldVal?.includes('Size')) {
                        // 移除 'Size'
                        this.attrs = attrs.filter(attr => attr !== 'Size')
                        this.model.sizes = []
                    } else if (!includesSize && oldVal?.includes('CupSize')) {
                        // 移除 'Cup'
                        this.attrs = attrs.filter(attr => attr !== 'Cup')
                        this.model.sizes = []
                    }

                    if (!includesColor && oldVal?.includes('Color')) {
                        // 清除选择的color
                        this.model.colors = []
                        this.fullColors = []
                    }
                    if (!includesSize && oldVal?.includes('CupSize')) {
                        // 清除 size cup
                        this.model.sizes = []
                        this.model.cups = []
                    }
                    if (!includesLetterSize && oldVal?.includes('Size')) {
                        // 清除 Size
                        this.model.sizes = []
                        this.fullLetterSizes = []
                    }
                    const diffValue = oldVal?.filter(item => !newVal.includes(item)) ?? []

                    if (diffValue.length > 0) {
                        const otherAttr = diffValue.filter(a => !['Color', 'Size', 'CupSize', 'Cup'].includes(a))
                        this.customList = this.customList.map(item => {
                            if (item.name === otherAttr[0]) {
                                item.data = []
                                item.fullList.map(pre => (pre.checked = false))
                            }
                            return { ...item }
                        })
                    }
                }
            },
            immediate: true,
        },
    },
    async created() {
        this.loading = true
        try {
            const [productTypeData, shopData, attrData] = await Promise.all([getAttrList(), getListingShop(), getSkuAttr()])
            this.dict.productTypeList = productTypeData?.data ?? []
            this.dict.shopList = shopData?.data ?? []
            const old_colors = attrData.data?.color?.old_color ?? []
            old_colors.map(pre => {
                pre.type = 'old'
                return { ...pre }
            })
            const new_colors = attrData.data?.color?.new_color ?? []
            new_colors.map(pre => {
                pre.type = 'new'
                return { ...pre }
            })
            this.dict.colorList = [].concat(old_colors).concat(new_colors)
            this.dict.sizeList = attrData.data?.sizes.size ?? []
            this.dict.letterSizeList = attrData.data?.sizes.letterSize ?? []
            this.dict.cupList = attrData.data?.cup ?? []
        } catch (error) {}
        this.loading = false

        this.model.id = this.$route.query.id
        if (this.model.id) {
            this.getDetail()
        }
    },
    methods: {
        copyImgToOther(type, row) {
            this.model.variant_json = this.model.variant_json.map(item => {
                if ((type === 'Color' && item.Color === row.Color) || (type === 'CupSize' && item.CupSize === row.CupSize) || (type === 'Cup' && item.Size === row.Size)) {
                    item.image_url = row.image_url
                }
                return { ...item }
            })
        },
        copyTitleToUrl() {
            this.model.seo_url = this.model.seo_title
        },
        showBatchDialog(type) {
            this.batchDialog.visible = true
            this.batchDialog.type = type
        },
        batchEditVariant(result) {
            this.model.variant_json = this.model.variant_json.map(item => {
                item[result.key] = result.value
                return { ...item }
            })
        },
        removeVariant(row) {
            this.isOperate = true
            this.model.variant_json = this.model.variant_json.filter(item => item.sku !== row.sku)
            if (this.model.variant_json.length > 0) {
                this.model.colors = this.model.colors.filter(item => item !== row.Color)
                this.model.sizes = this.model.sizes.filter(item => item !== row.CupSize)
                this.model.cups = this.model.cups.filter(item => item !== row.Cup)
                this.customList.forEach(item => {
                    if (item.name == row[item.name]) {
                        item.data = item.data.filter(item => item !== row[item.name])
                    }
                })
            }
            this.isOperate = false
        },
        showSeoTemp() {
            this.showSeo = !this.showSeo
            // if (!this.showSeo) {
            //     this.model.seo_title = ''
            //     this.model.seo_desc = ''
            //     this.model.seo_url = ''
            // }
        },
        selectShop() {
            const item = this.dict.shopList.find(item => item.shop_id === this.model.shop_id)
            this.myshopify_domain = item?.myshopify_domain ?? ''
        },
        remoteQueryCollection(keyword) {
            this.getCollections(keyword)
        },
        async getCollections(keyword) {
            try {
                const params = { shop_id: this.model.shop_id, keyword }
                const collectionData = await getCollections(params)
                this.dict.collectionList = collectionData?.data ?? []
            } catch (error) {}
        },
        addCustomAttr(name, fullList, data) {
            const attrName = this.attrName || name
            if (!attrName) {
                return this.$message.warning('请输入属性名称')
            }
            const hasExist = this.attrs.includes(attrName)
            if(!hasExist) {
                this.attrs.push(attrName)
            }
            const customItem = deepClone(this.customDefault)
            customItem.name = attrName
            if (fullList) {
                customItem.fullList = fullList
            }
            if (data) {
                customItem.data = data
            }

            this.customList.push(customItem)
            this.attrName = ''
        },

        addCustom() {
            this.customList.push(this.customDefault)
        },
        deleteCustom(index) {
            this.customList.splice(index, 1)
        },
        addCustomItem(value, item) {
            if (!value) {
                return this.$message.warning('请输入属性值')
            }
            const index = item.fullList.findIndex(pre => pre.id === value)
            if (index == -1) {
                item.fullList.push({ attr_name: value, id: value, checked: true })
                item.data.push(value)
            } else {
                item.fullList.splice(index, 1)
                item.data.splice(index, 1)
            }
            item.value = ''

            this.$forceUpdate()
        },

        deleteCustomItem(item, list) {
            const index = list.findIndex(pre => pre.id === item.id)
            if (index != -1) {
                list.splice(index, 1)
            }
            this.$forceUpdate()
        },
        addLetterSize() {
            if (!this.customLetterSize) {
                return
            }
            const uuid = Math.random().toString(36).slice(-8)
            const newItem = { id: uuid, attr_name: this.customLetterSize, type: 'new' }
            this.customLetterSize = ''
            this.dict.letterSizeList.push(newItem)
            this.selectLetterSizes(newItem)
        },
        deleteLetterSize(item) {
            const index = this.fullLetterSizes.findIndex(pre => pre.id == item.id)
            if (index != -1) {
                this.fullLetterSizes.splice(index, 1)
                this.model.sizes.splice(index, 1)
            }
            const dictIndex = this.dict.letterSizeList.findIndex(pre => pre.id == item.id)
            if (dictIndex != -1) {
                this.dict.letterSizeList.splice(dictIndex, 1)
            }
            this.loading = false
        },
        selectLetterSizes(item) {
            const index = this.fullLetterSizes.findIndex(pre => pre.id === item.id)
            if (index == -1) {
                this.fullLetterSizes.push({ attr_name: item.attr_name, id: item.id, checked: true })
                this.model.sizes.push(item.attr_name)
            } else {
                this.fullLetterSizes.splice(index, 1)
                this.model.sizes.splice(index, 1)
            }
            this.$forceUpdate()
        },
        async addColor() {
            if (!this.customColor) {
                return
            }
            this.loading = true

            const res = await addColor({ color_name: this.customColor })
            this.$message.success(res.msg)
            const newItem = { id: res.data.id, attr_name: res.data.color_name, type: 'new', checked: true }
            this.dict.colorList.push(newItem)
            this.selectColors(newItem)
            this.customColor = ''

            this.loading = false
        },
        async deleteColor(item) {
            this.loading = true
            const res = await deleteColor({ color_id: item.id })
            this.$message.success(res.msg)
            const index = this.fullColors.findIndex(pre => pre.id == item.id)
            if (index != -1) {
                this.fullColors.splice(index, 1)
                this.model.colors.splice(index, 1)
            }
            const dictIndex = this.dict.colorList.findIndex(pre => pre.id == item.id)
            if (dictIndex != -1) {
                this.dict.colorList.splice(dictIndex, 1)
            }
            this.loading = false
        },
        isChecked(id, list) {
            return list.findIndex(item => item.id === id && item.checked) > -1
        },
        selectDiameter(item, temp) {
            const index = temp.fullList.findIndex(pre => pre.id === item.id)
            if (index == -1) {
                temp.fullList.push({ attr_name: item.attr_name, id: item.id, checked: true })
                temp.data.push(item.attr_name)
            } else {
                const obj = temp.fullList[index]
                obj.checked = !obj.checked
                temp.fullList.splice(index, 1, obj)
                temp.data.splice(index, 1, obj.attr_name)
            }
            this.$forceUpdate()
        },
        selectColors(item) {
            const index = this.fullColors.findIndex(pre => pre.id === item.id)
            if (index == -1) {
                this.fullColors.push({ attr_name: item.attr_name, id: item.id, checked: true })
                this.model.colors.push(item.attr_name)
            } else {
                this.fullColors.splice(index, 1)
                this.model.colors.splice(index, 1)
            }
            this.$forceUpdate()
        },
        showSeniorDialog() {
            if (this.model.variant_json.length == 0) {
                return this.$message.error('变种信息SKU为空，无法使用高级生成')
            }
            this.seniorVisible = true
            this.modelSenior = Object.assign(this.modelSenior, this.model.variant_json[0])
            this.modelSenior.before_character = this.modelSenior.character
            const { colors, sizes, cups } = this.model
            let attrList = [
                {
                    name: 'Color',
                    data: colors.map(pre => {
                        return { value: pre, editValue: pre }
                    }),
                },
                {
                    name: 'CupSize',
                    data: sizes.map(pre => {
                        return { value: pre, editValue: pre }
                    }),
                },
                {
                    name: 'Cup',
                    data: cups.map(pre => {
                        return { value: pre, editValue: pre }
                    }),
                },
            ]
            const customList = this.customList.map(custom => {
                return {
                    name: custom.name,
                    data: custom.data.map(pre => {
                        return { value: pre, editValue: pre }
                    }),
                }
            })
            attrList = attrList.concat(customList)
            this.modelSenior.attrList = attrList.filter(item => item.data.length > 0)
            this.getPreviewValue()
        },
        getPreviewValue(value) {
            if (value) {
                this.$forceUpdate()
            }

            const prefix = this.modelSenior.prefix ? this.modelSenior.prefix + this.modelSenior.character : ''
            let content = ''
            this.modelSenior?.attrList?.map((item, index) => {
                if (index == 0 || item.name == 'Cup') {
                    content += item.data[0].editValue
                } else {
                    content += this.modelSenior.character + item.data[0].editValue
                }
            })
            const Color = this.modelSenior?.attrList?.find(item => item.name == 'Color')?.data?.[0]?.editValue
            content = this.transformSKU(Color, content)

            const suffix = this.modelSenior.suffix ? this.modelSenior.character + this.modelSenior.suffix : ''
            this.modelSenior.previewValue = `${prefix}${content}${suffix}`
        },
        seniorSave() {
            const attrList = this.calcDescartesUpdate()
            this.model.variant_json.map(item => {
                const tempInfo = attrList.find(temp => temp.before_sku === item.before_sku) ?? {}
                item = Object.assign(item, tempInfo)
                return { ...item }
            })
            this.seniorVisible = false
        },
        setVariantArr() {
            const attrList = this.calcDescartes()
            const beforeAttrList = deepClone(this.model.variant_json)
            this.model.variant_json = []
            attrList.forEach(item => {
                const index = beforeAttrList.findIndex(temp => temp.key === item.key)
                const beforeItem = beforeAttrList.find(temp => temp.key === item.key)
                if (index == -1) {
                    this.model.variant_json.push(item)
                } else {
                    this.model.variant_json.push(beforeItem)
                }
            })
        },
        transformSKU(Color, sku) {
            if (Color && Color.indexOf('-') != -1) {
                const num = Color.split('-')[1]
                const [color, other] = sku.split(`-${num}`)
                sku = `${color}${other}-${num}`
            }
            return sku
        },
        calcDescartes() {
            const { colors, sizes, cups } = this.model
            let result = []
            const defaultItem = {
                sku: '',
                before_sku: '',
                prefix: '',
                suffix: '',
                character: '-',
                Color: '',
                CupSize: '',
                Cup: '',
            }
            let list = [{ name: 'Color', data: colors }]

            if (this.attrs.includes('Size')) {
                list.push({ name: 'Size', data: sizes })
            } else if (this.attrs.includes('CupSize')) {
                list = list.concat([
                    { name: 'CupSize', data: sizes },
                    { name: 'Cup', data: cups },
                ])
            }

            const customList = this.customList.map(pre => ({
                name: pre.name,
                data: pre.data,
            }))
            list = list.concat(customList)
            const filterList = list.filter(item => item.data.length > 0)
            const dataCount = filterList.length
            const formateItem = ({ item = {}, defaultItem, currentKey, currentData }) => {
                return currentData.map(value => ({
                    ...item,
                    [currentKey]: value,
                    key: `${item?.sku ?? ''}${item.sku ? '-' : ''}${value}`,
                    sku: `${item?.sku ?? ''}${item.sku && currentKey != 'Cup' ? defaultItem.character : ''}${value}`,
                    before_sku: `${item?.before_sku ?? ''}${item.before_sku && currentKey != 'Cup' ? defaultItem.character : ''}${value}`,
                }))
            }
            if (dataCount == 0) {
                result = []
            } else if (dataCount == 1) {
                const currentKey = filterList[0].name
                const currentData = filterList[0].data
                result = formateItem({ defaultItem, currentKey, currentData })
            } else {
                result = filterList.reduce(
                    (accumulator, currentMap) => {
                        const currentKey = currentMap.name
                        const currentData = currentMap.data
                        return accumulator.flatMap(item => formateItem({ item, defaultItem, currentKey, currentData }))
                    },
                    [defaultItem],
                )
            }
            result = result.map(item => {
                item.sku = this.transformSKU(item.Color, item.sku)
                return { ...item }
            })
            return result
        },
        calcDescartesUpdate() {
            const { prefix, suffix, character, before_character } = this.modelSenior
            const prefixChar = prefix ? prefix + character : ''
            const suffixChar = suffix ? character + suffix : ''

            let result = []

            const filterList = this.modelSenior.attrList.filter(item => item.data.length > 0)
            const dataCount = filterList.length

            const formateItem = ({ item = {}, currentKey, currentData }) => {
                return currentData.map(temp => ({
                    ...item,
                    character,
                    prefix,
                    suffix,
                    [currentKey]: temp.editValue,
                    sku: `${item?.sku ?? ''}${item.sku && currentKey != 'Cup' ? character : ''}${temp.editValue}`,
                    before_sku: `${item?.before_sku ?? ''}${item.before_sku && currentKey != 'Cup' ? before_character : ''}${temp.value}`,
                }))
            }
            if (dataCount == 0) {
                result = []
            } else if (dataCount == 1) {
                const currentKey = filterList[0].name
                const currentData = filterList[0].data
                result = formateItem({ currentKey, currentData })
            } else {
                result = filterList.reduce(
                    (accumulator, currentMap) => {
                        const currentKey = currentMap.name
                        const currentData = currentMap.data
                        return accumulator.flatMap(item => formateItem({ item, currentKey, currentData }))
                    },
                    [{}],
                )
            }

            result = result.map(item => {
                item.sku = this.transformSKU(item.Color, item.sku)
                item.sku = `${prefixChar}${item.sku}${suffixChar}`
                return { ...item }
            })
            return result
        },

        getDetail() {
            this.loading = true
            const params = { id: this.model.id }
            getInfo(params)
                .then(res => {
                    this.model = Object.assign({}, this.model, res.data)

                    if (this.model.product_images.length > 0) {
                        this.model.product_images = this.model.product_images.map(item => item.src)
                    }

                    if (this.model.collections_tag) {
                        this.model.collections_tag = this.model.collections_tag.split(',')
                    }
                    if (this.model.product_tags) {
                        this.model.product_tags = this.model.product_tags.split(',')
                    }
                    
                    this.isOperate = true
                    if(this.isMultipleSku) {
                        const options = this.model.options ? JSON.parse(this.model.options) : []
                    if (this.model.variant_json.length > 0) {
                        this.model.variant_json = this.model.variant_json.map(item => {
                            options.forEach(option => {
                                if (option.position == 1) {
                                    item[option.name] = item.option1
                                } else if (option.position == 2) {
                                    item[option.name] = item.option2
                                } else if (option.position == 3) {
                                    item[option.name] = item.option3
                                }
                                })
                                // 反解高级编辑sku所需额外参数
                                item.character = this.getMostRepeatedNonDigitChar(item.sku)
                                item.key = item.sku
                                const chatList = item.sku?.split(item.character) ?? []
                                item.prefix = this.isExtraChart(item, chatList[0]) ? chatList[0] : ''
                                item.suffix = this.isExtraChart(item, chatList[chatList.length - 1]) ? chatList[chatList.length - 1] : ''
                                const skuList = chatList.filter(chat => chat!=item.prefix && chat!=item.suffix)
                                if(item?.Color.indexOf('-') > -1) {
                                    const itemList = [item.Color].concat(skuList.filter(s=>item.Color.indexOf(s)==-1))
                                    item.before_sku = itemList.join(item.character)
                                } else {
                                    item.before_sku = skuList.join(item.character)
                                }
                                return { ...item }
                            })
                            this.showStockSupport = this.model.variant_json.some(item => !!item.inventory_support)
                        }
                        if (options.length > 0) {
                            this.attrs = options.map(item => item.name).filter(item => item != 'Cup')
                                options.map(item => {
                                    if (item.values.length > 0) {
                                        if (item.name === 'Color') {
                                            this.model.colors = item.values
                                            this.model.colors.map(attr_name => {
                                                const temp = this.dict.colorList?.find(item => item.attr_name === attr_name) ?? {}
                                                this.fullColors.push({ attr_name: temp.attr_name, id: temp.id, checked: true })
                                            })
                                    } else if (item.name === 'Size') {
                                        this.model.sizes = item.values
                                        this.model.sizes.map(attr_name => {
                                            const temp = this.dict.letterSizeList?.find(item => item.attr_name === attr_name) ?? {}
                                            this.fullLetterSizes.push({ attr_name: temp.attr_name, id: temp.id, checked: true })
                                        })
                                    } else if (item.name === 'CupSize') {
                                        this.model.sizes = item.values
                                    } else if (item.name === 'Cup') {
                                        this.model.cups = item.values
                                    } else {
                                        const fullList = item.values.map(attr=>{
                                            const uuid = Math.random().toString(36).slice(2)
                                            return { attr_name: attr, id: uuid, checked: true }
                                        })
                                        this.addCustomAttr(item.name, fullList, item.values)
                                    }
                                }
                            })
                        }
                    }
                    if(this.isSingleSku) {
                        const row = this.model.variant_json[0]
                        this.model.sku = row.sku
                        this.model.price = row.price
                        this.model.weight = row.weight
                        this.model.compare_at_price = row.compare_at_price
                        this.model.inventory_quantity = row.inventory_quantity
                        this.model.inventory_support = row.inventory_support
                        this.model.barcode = row.barcode
                    }
                    
                    if (this.model.seo_title || this.model.seo_desc || this.model.seo_url) {
                        this.showSeo = true
                    }
                    this.$nextTick(() => {
                        this.isOperate = false
                    })
                })
                .finally(() => {
                    this.loading = false
                })
        },
        isExtraChart(item, chart) {
            return chart.indexOf(item.option1) == -1 && chart.indexOf(item.option2) == -1 && chart.indexOf(item.option3) == -1
        },
        getMostRepeatedNonDigitChar(str) {
            if(!str) {
                return '-'
            }
            // 使用正则表达式提取非数字字母
            const nonDigitChars = str.match(/[^a-zA-Z0-9]/g)
            if (!nonDigitChars) {
                return '-'
            }
            const charCount = {}
            // 统计每个字符的出现次数
            for (const char of nonDigitChars) {
                charCount[char] = (charCount[char] || 0) + 1
            }
            // 找到出现次数最多的字符
            let maxChar = null
            let maxCount = 0
            for (const char in charCount) {
                if (charCount[char] > maxCount) {
                    maxChar = char
                    maxCount = charCount[char]
                }
            }
            return maxChar
        },
        submit() {
            if (this.attrs.length > 3) {
                return this.$message.error('最多选择3个属性')
            }
            this.$refs.form.validate(valid => {
                if (!valid) {
                    return
                }

                const params = { ...this.model }
                if (typeof params.product_images === 'string') {
                    params.product_images =
                        params?.product_images?.split(',')?.map((item, index) => {
                            return {
                                position: index + 1,
                                src: item,
                                width: 800,
                                height: 1000
                            }
                        }) ?? []
                } else if (Array.isArray(params.product_images)) {
                    params.product_images =
                        params?.product_images?.map((item, index) => {
                            return {
                                position: index + 1,
                                src: item,
                                width: 800,
                                height: 1000
                            }
                        }) ?? []
                }
                
                if (this.isMultipleSku) {
                    const attrs = deepClone(this.attrs)
                    if (attrs.includes('CupSize') && !attrs.includes('Cup')) {
                        const size_index = attrs.findIndex(item => item === 'CupSize')
                        attrs.splice(size_index + 1, 0, 'Cup')
                    }

                params.options = attrs.map((item, index) => {
                    let values = []
                    switch (item) {
                        case 'Color':
                            values = this.model.colors
                            break
                        case 'Size':
                            values = this.model.sizes
                            break
                        case 'CupSize':
                            values = this.model.sizes
                            break
                        case 'Cup':
                            values = this.model.cups
                            break
                        default:
                            values = this.customList.map(tem => tem.name == item)?.data ?? []
                            break
                    }
                    return {
                        name: item,
                        position: index + 1,
                        values: values,
                    }
                })
                    params.variant_json = params.variant_json.map(item => {
                        attrs.map((attr, index) => {
                            item[`option${index + 1}`] = item[attr]
                            delete item[attr]
                        })

                        delete item.before_sku
                        delete item.character
                        delete item.key
                        delete item.prefix
                        delete item.suffix
                        for (let key in item) {
                            if (!item[key]) {
                                delete item[key]
                            }
                        }
                        return { ...item }
                    })
                }
                if(this.isSingleSku) {
                    params.options = [
                        {
                            name: 'Default Title',
                            position: 1,
                            values: ['Default Title']
                        }
                    ]
                    params.variants = [{
                        position: 1,
                        option1: 'Default Title',
                        sku: params.sku,
                        price: params.price,
                        compare_at_price: params.compare_at_price,
                        inventory_quantity: params.inventory_quantity,
                        inventory_support: params.inventory_support,
                        weight: params.weight,
                        barcode: params.barcode,
                    }]
                    params.variant_json = params.variants
                }

                if (Array.isArray(params.collections_tag)) {
                    params.collections_tag = params.collections_tag?.join(',') ?? ''
                }
                if (Array.isArray(params.product_tags)) {
                    params.product_tags = params.product_tags?.join(',') ?? ''
                }
                delete params.colors
                delete params.sizes
                delete params.cups
                if (!this.isPrivate) {
                    delete params.supply_shop_name
                    delete params.shop_id
                    delete params.seo_title
                    delete params.seo_desc
                    delete params.seo_url
                }
                if (this.save) {
                    return
                }
                this.save = true
                const request = this.model.id ? edit : add
                request(params)
                    .then(res => {
                        this.$message.success(res.msg)
                        this.$emit('success')
                        this.cancel()
                    })
                    .finally(() => {
                        this.save = false
                    })
            })
        },
        cancel() {
            this.$emit('cancel')
        },
    },
}
</script>

<style lang="scss" scoped>
.online-detail {
    .header {
        padding-bottom: 8px;
        border-bottom: 1px solid #f5f5f5;
        margin-bottom: 16px;

        .header-title {
            margin-left: 16px;
            font-size: 16px;
        }
    }
    .card {
        padding: 12px 16px;
    }

    .card + .card {
        margin-top: 12px;
    }
    .card > .title {
        padding-bottom: 16px;
        border-bottom: 1px solid #f5f5f5;
        margin: 0;
        margin-bottom: 12px;
        text-align: left;
        color: #333;
    }
    .el-form-item {
        width: calc(100% - 10px);
        .el-cascader,
        .el-select,
        .el-textarea,
        .el-input {
            width: 100%;
        }
    }
    .el-form-item.half {
        width: calc(50% - 10px);
        .el-cascader,
        .el-select,
        .el-input {
            width: 100%;
        }
    }
}
::v-deep {
    .el-form-item {
        &.half {
            .el-form-item__content {
                width: 70%;
            }
        }
        .el-form-item__content {
            width: 85%;
        }
    }
}
.item-card {
    border: 1px solid #f5f5f5;
    padding: 8px;
}
.ml_12 {
    margin-left: -12px;
}
</style>
